# test_agents.py
import sys
import os

# 添加模块路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from agents.intent_classifier import IntentRecognitionAgent
from agents.sql_generator import SQLGenerationAgent
from models.state import WorkflowState

def interactive_test():
    """
    交互式测试意图识别和SQL生成模块
    """
    print("=" * 60)
    print("意图识别 + SQL生成 交互式测试")
    print("=" * 60)
    
    # 初始化两个agent
    intent_agent = IntentRecognitionAgent()
    sql_agent = SQLGenerationAgent()
    
    while True:
        print("\n" + "-" * 40)
        user_input = input("请输入您的问题 (输入 'quit' 退出): ").strip()
        
        if user_input.lower() in ['quit', 'exit', '退出']:
            print("感谢使用，再见！")
            break
            
        if not user_input:
            print("输入不能为空，请重新输入。")
            continue
        
        print(f"\n用户输入: {user_input}")
        
        # 初始化状态
        state = WorkflowState(user_input=user_input)
        
        # 第一步：意图识别
        print("\n>>> 正在进行意图识别...")
        state = intent_agent.process(state)
        
        intent_result = state.intent
        intent_details = state.intent_details or {}
        
        print(f"意图识别结果: {intent_result}")
        
        # 如果是other意图且需要澄清
        if intent_result == "other" and intent_details.get('waiting_for_clarification', False):
            clarification_question = intent_details.get('clarification_question', '')
            print(f"澄清询问: {clarification_question}")
            
            # 获取用户澄清回复
            clarification_response = input("请回复澄清问题: ").strip()
            
            if clarification_response.lower() in ['quit', 'exit', '退出']:
                print("感谢使用，再见！")
                break
                
            if not clarification_response:
                print("回复不能为空，请重新输入。")
                continue
            
            # 使用澄清回复重新进行意图识别
            print(f"\n澄清回复: {clarification_response}")
            state.user_input = clarification_response
            state = intent_agent.process(state)
            
            intent_result = state.intent
            intent_details = state.intent_details or {}
            
            print(f"澄清后意图识别结果: {intent_result}")
        
        # 如果最终意图还是other，跳过SQL生成
        if intent_result == "other":
            print("无法识别有效意图，跳过SQL生成。")
            continue
        
        # 第二步：SQL生成
        print("\n>>> 正在进行SQL生成...")
        state = sql_agent.process(state)
        
        generated_sql = state.generated_sql
        print(f"生成的SQL语句: {generated_sql}")

if __name__ == "__main__":
    # 如果缺少必要的依赖，需要先创建基本的类结构
    try:
        interactive_test()
    except Exception as e:
        print(f"测试过程中出现错误: {e}")
        print("可能需要先创建必要的依赖类...")
        
        # 创建基本的WorkflowState类（如果不存在）
        class WorkflowState:
            def __init__(self, user_input=""):
                self.user_input = user_input
                self.intent = None
                self.intent_details = {}
                self.entities = {}
                self.schema_info = {}
                self.generated_sql = None
        
        print("已创建基础依赖，重新运行测试...")
        interactive_test()